package com.oocl.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class ImageUtil {
	public static String generateString(byte[] img) {
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(img);

	}

	public static String generateStringFromFile(String filePath) {
		FileInputStream in = null;
		try {
			in = new FileInputStream(filePath);
			byte[] buf = new byte[in.available()];
			in.read(buf);
			return generateString(buf);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	// 将文件保存到指定文件夹
	public static void generateImage(String img, String imgFilePath) {
		BASE64Decoder decoder = new BASE64Decoder();
		OutputStream out = null;
		try {
			// Base64解码
			byte[] bytes = decoder.decodeBuffer(new String(img));
			out = new FileOutputStream(imgFilePath);
			out.write(bytes);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
